<template>
  <a-config-provider :locale="locale">
    <div id="app">
      <router-view v-if="isRouterAlive" />
    </div>
  </a-config-provider>
</template>

<script>
import { domTitle, setDocumentTitle } from '@/utils/domUtil'
import { i18nRender } from '@/locales'
import zh_CN from 'ant-design-vue/lib/locale-provider/zh_CN'
import moment from 'moment'
import 'moment/locale/zh-cn'

// 水印工具
import watermark from 'watermark-dom'
import { APP_USER, VUE_APP_SOCKET_URL } from '@/store/mutation-types.js'
import storage from 'store'

moment.locale('zh-cn')

export default {
  // 新增当前路由刷新的功能，可以在下局所有组件内生效
  provide () {
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      zh_CN,
      isRouterAlive: true,
      currentUser: storage.get(APP_USER),
      fontSize: 14, // 字号大小

      // websocket的心跳配置
      timeout: 20 * 1000, // 20秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
      websocket: null
    }
  },
  watch: {
    // 切换路由重新加载
    $route (to, from) {
      const path = [
        'AppeptExamineProcessedOperation',
        'AppeptExamineHandleOperation',
        'SuperviseTodoOpearation',
        'AcceptRecordHandleOperation',
        'HearExamineProcessedOperation',
        'HearExamineHandleOperation',
        'ArriveInfoHandleOperation',
        'ArriveInfoProcessedOperation',
        'ArriveInfoHandleSupOperation'
      ]
      console.log(to.name)

      const layoutEle = document.querySelector('.ant-layout-content')
      console.log(layoutEle)
      if (path.includes(to.name)) {
        console.log(11111111111111)
        layoutEle.style.padding = '0px'
      } else {
        layoutEle.style.padding = '10px 24px 0px 24px'
      }
      // 给首页菜单加阴影
      // const arr = ['ha_enumerationList', 'ha_roleList']
      // console.log(arr)
      // if (arr.includes(to.name)) {
      //   console.log(2222)
      //   const myElement = this.$el.querySelector('.ant-menu')
      //   myElement.style.boxShadow = '0px 0px 35px 0px rgba(232, 232, 232, 0.59)'
      //   myElement.style.background = '#F5F6FA'
      // }
      this.addWaterMark()
      // 当前的websocket的连接对象为空
      if (!this.websocket) {
        this.initWebSocket()
        window.addEventListener('onmessageWS', this.getSocketData)
      }
    }
  },
  mounted () {
    this.addWaterMark()
    this.initWebSocket()
    window.addEventListener('onmessageWS', this.getSocketData)
  },
  created () {
    document.documentElement.style.fontSize = this.fontSize + 'px'
  },
  computed: {
    locale () {
      // 只是为了切换语言时，更新标题
      const { title } = this.$route.meta
      title && setDocumentTitle(`${i18nRender(title)} - ${domTitle}`)
      return this.$i18n.getLocaleMessage(this.$store.getters.lang).antLocale
    }
  },
  methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    },
    addWaterMark () {
      setTimeout(() => {
        this.currentUser = storage.get(APP_USER)
        if (this.currentUser) {
          const content = this.currentUser.fullname + moment().format('YYYY年MM月DD日')
          // watermark_id: 'wm_div_id',          //水印总体的id
          // watermark_prefix: 'mask_div_id',    //小水印的id前缀
          // watermark_txt:"测试水印",             //水印的内容
          // watermark_x:20,                     //水印起始位置x轴坐标
          // watermark_y:20,                     //水印起始位置Y轴坐标
          // watermark_rows:0,                   //水印行数
          // watermark_cols:0,                   //水印列数
          // watermark_x_space:100,              //水印x轴间隔
          // watermark_y_space:50,               //水印y轴间隔
          // watermark_font:'微软雅黑',           //水印字体
          // watermark_color:'black',            //水印字体颜色
          // watermark_fontsize:'18px',          //水印字体大小
          // watermark_alpha:0.15,               //水印透明度，要求设置在大于等于0.005
          // watermark_width:100,                //水印宽度
          // watermark_height:100,               //水印长度
          // watermark_angle:15,                 //水印倾斜度数
          // watermark_parent_width:0,      //水印的总体宽度（默认值：body的scrollWidth和clientWidth的较大值）
          // watermark_parent_height:0,     //水印的总体高度（默认值：body的scrollHeight和clientHeight的较大值）
          // watermark_parent_node:null     //水印插件挂载的父元素element,不输入则默认挂在body上
          watermark.init({
            watermark_txt: content,
            watermark_x_space: 100,
            watermark_width: 200,
            watermark_alpha: 0.07
          })
        }
      }, 1000)
    },
    initWebSocket () {
      this.currentUser = storage.get(APP_USER)
      if (this.currentUser) {
        console.log('websocket地址', VUE_APP_SOCKET_URL)
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        const wsUrl = VUE_APP_SOCKET_URL + this.currentUser.userId
        this.websocket = new WebSocket(wsUrl)
        this.websocket.onopen = this.websocketonopen
        this.websocket.onerror = this.websocketonerror
        this.websocket.onmessage = this.setOnmessageMessage
        this.websocket.onclose = this.websocketclose
        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        // window.onbeforeunload = that.onbeforeunload
      }
    },
    start () {
      console.log('start')
      const that = this
      // 清除延时器
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        console.log('this.websocket :', this.websocket)
        if (that.websocket && that.websocket.readyState == 1) {
          console.log('进入发送心跳包')
          that.websocket.send('heartbreath') // 发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
        } else {
          console.log('心跳包失败，重新链接')
          that.reconnect()
        }
        // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          this.websocket.close()
        }, this.timeout)
      }, this.timeout)
    },
    reset () {
      // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      // 重启心跳
      this.start()
    },
    // 重新连接
    reconnect () {
      if (this.lockReconnect) return
      this.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum)
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket()
        this.lockReconnect = false
      }, this.timeout)
    },
    async setOnmessageMessage (event) {
      console.log(event.data, '获得消息')
      this.reset()
      // 自定义全局监听事件
      window.dispatchEvent(
        new CustomEvent('onmessageWS', {
          detail: {
            data: event.data
          }
        })
      )
      // //发现消息进入    开始处理前端触发逻辑
      // if (event.data === 'success' || event.data === 'heartBath') return
    },
    /**
     * 消息通知
     * @param {} event
     * {
     *    id,
     *    content:
     *    userid:
     *    msgtype:
     *    router
     * }
     */
    getSocketData (event) {
      if (event.detail && event.detail.data) {
        let detailObj
        try {
          detailObj = JSON.parse(event.detail.data)
        } catch (error) {
          console.log('当前的消息非josn格式:', event.detail.data)
          return
        }
        this.$notification.info({
          message: `提醒`,
          placement: 'bottomRight',
          description: `${detailObj.content}`,
          onClick: () => {
            console.log('点击事件')
            if (detailObj.router && JSON.parse(detailObj.router)) {
              const router = JSON.parse(detailObj.router)
              this.$router.push(router)
              // const path = detailObj.router
              // const url = detailObj.queryurl ? detailObj.queryurl : ''
              // const queryParam = detailObj.queryparam ? detailObj.queryparam : ''
              // this.$router.push({
              //   path: path,
              //   query: {
              //     url: url,
              //     queryParam: queryParam
              //   }
              // })
            }
          }
        })
      }
    },
    websocketonopen () {
      // 开启心跳
      const that = this
      let timer
      timer = setInterval(function () {
        that.start()
      }, that.timeout)
      // this.start();   //因为我这边一直报心跳延时，所以我添加了setInterval来发送心跳
      console.log('WebSocket连接成功!!!' + new Date() + '///////////' + this.websocket.readyState)
    },
    websocketonerror (e) {
      console.log('WebSocket连接发生错误' + e)
    },
    websocketclose (e) {
      this.websocket.close()
      this.websocket = null
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      console.log('WebSocket连接关闭')
    },
    websocketsend (messsage) {
      const that = this
      that.websocket.send(messsage)
    },
    closeWebSocket () {
      // 关闭websocket
      const that = this
      that.websocket.close()
    }
  }
}
</script>

<style lang="less" scoped>
// 左侧菜单栏颜色调整
::v-deep .ant-layout-sider-children .ant-menu,
.ant-layout-sider-children .ant-menu-light {
  background-color: #f5f6fa !important;
}
// 路由容器边距和背景调整
::v-deep .ant-layout-content,
.ant-pro-basicLayout-content {
  margin: 0;
  padding: 10px 24px 0px 24px;
  background-color: #f5f6f9;
}
::v-deep .ant-layout-sider-children .ant-menu-submenu-title,
::v-deep .ant-layout-sider-children .ant-menu-item {
  font-size: 16px;
  font-weight: bold;
}
::v-deep .ant-menu-item a {
  // padding: 0 16px 0 12px;
}
::v-deep .ant-menu-light {
  height: 93vh;
  overflow: auto;
  overflow-x: hidden;
}
::v-deep .ant-layout-footer {
  display: none !important;
}
::v-deep .ant-tabs-nav-wrap {
  height: 38px;
  line-height: 15px;
}
/deep/ .tabs-container {
  height: 100px;
}
::v-deep .ant-layout .sidemenu {
  // overflow: hidden !important;
}
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
#app {
  height: 100%;
  width: 100%;
  overflow: hidden;
}
::v-deep .ant-layout {
  height: 10px;
}
::v-deep .ant-layout-header {
  z-index: 105 !important;
}

::v-deep .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active {
  color: #0072c6;
  background: #ffffff !important;
}
::v-deep .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab {
  background: #f2f8fd;
  height: 36px;
  line-height: 36px;
}
::v-deep .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-nav-container {
  height: 36px;
}
::v-deep .ant-tabs-nav .ant-tabs-tab:hover {
  color: #0072c6 !important;
}

::v-deep .ant-btn-primary {
  color: #fff !important;
  background: #0072c6 !important;
  border: 2px solid #0072c6 !important;
  border-radius: 5px !important;
}
::v-deep .ant-btn-primary:hover,
::v-deep .ant-btn-primary:focus {
  background-color: #0072c6 !important;
  opacity: 0.8 !important;
  color: #fff !important;
  border: 2px solid #0072c6 !important;
}
::v-deep .ant-btn {
  color: #0072c6;
  background: #fff;
  border: 1px solid #0072c6;
  border-radius: 5px;
}
::v-deep .ant-btn:hover,
::v-deep .ant-btn:focus {
  background-color: #fff;
  opacity: 0.8;
  color: #0072c6;
  border: 1px solid #0072c6;
}

::v-deep .ant-pagination-item-active {
  background: #0072c6;
}
::v-deep .ant-pagination-item-active a {
  color: #fff;
}
::v-deep .ant-pagination-item-active:focus a,
.ant-pagination-item-active:hover a {
  color: #fff;
}
</style>
<style>
/* 没有scoped的style不需要使用 ：：deep */
.ant-btn-primary {
  color: #fff !important;
  background: #0072c6 !important;
  border: 2px solid #0072c6 !important;
  border-radius: 5px !important;
}
.ant-btn-primary:hover,
.ant-btn-primary:focus {
  background-color: #0072c6 !important;
  opacity: 0.8 !important;
  color: #fff !important;
  border: 2px solid #0072c6 !important;
}
button.ant-btn {
  color: #0072c6;
  background: #fff;
  border: 1px solid #0072c6;
  border-radius: 5px;
}
.ant-btn:hover,
.ant-btn:focus {
  background-color: #fff;
  opacity: 0.8;
  color: #0072c6;
  border: 1px solid #0072c6;
}
.ant-table-tbody > tr:hover:not(.ant-table-expanded-row) > td,
.ant-table-row-hover,
.ant-table-row-hover > td {
  background-color: #eff3f6 !important;
}

.ant-table-fixed .ant-table-row-hover,
.ant-table-row-hover > td {
  background-color: #eff3f6 !important;
}

.ant-table-pagination.ant-pagination {
  margin: 16px 10px;
}

.ant-pagination-options-quick-jumper {
  margin-right: 10px;
}
</style>
